#include "Mystring.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void Print(Mystring *obj);
int IsEqual(Mystring *obj1, Mystring *obj2);
int IsContains(Mystring *dest, Mystring *);
int Size(Mystring *obj);
void RemoveString(Mystring *dest, const char *str);
void InsertString(Mystring *dest, const char *str, int index);

void Initialize(Mystring *obj, const char *str)
{

    obj->size = strlen(str);
    obj->string = (char *)malloc(sizeof(char) * (obj->size + 1));
    if (obj->string == NULL)
    {
        printf("Mystring malloc error!\n");
        return;
    }
    strcpy(obj->string, str);
    obj->print = Print;
    obj->isContains = IsContains;
    obj->isEqual = IsEqual;
    obj->stringSize = Size;
    obj->insertString = InsertString;
    obj->removeString = RemoveString;
}

void FreeMyString(Mystring *obj)
{
    if (obj->string != NULL)
    {
        free(obj->string);
        obj->string = NULL;
    }
}

void Print(Mystring *obj)
{
    printf("%s\n", obj->string);
}

int IsEqual(Mystring *obj1, Mystring *obj2)
{
    if (strcmp(obj1->string, obj2->string) == 0)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

int IsContains(Mystring *dest, Mystring *src)
{
    char *str = strstr(dest->string, src->string);
    if (str == NULL)
    {
        return 0;
    }
    else
    {
        return 1;
    }
}

int Size(Mystring *obj)
{
    return obj->size;
}

void RemoveString(Mystring *dest, const char *str)
{
    char *RMstr = strstr(dest->string, str);
    if (RMstr == NULL)
    {
        return;
    }
    else
    {
        char *destination = RMstr + strlen(str);
        while (*destination != '\0')
        {
            *RMstr = *destination;
            RMstr++;
            destination++;
            *RMstr = '\0';
        }
    }
}

void InsertString(Mystring *dest, const char *str, int index)
{
    if (index < 0 || index > dest->size)
    {
        return;
    }
    int new_str_len = dest->size + strlen(str) + 1;
    char *new_str = (char *)malloc(new_str_len);
    if (new_str == NULL)
    {
        printf("insertstring malloc error");
        return;
    }
    strncpy(new_str, dest->string, index);
    strncpy(new_str + index, str, strlen(str));
    strcpy(new_str + index + strlen(str), dest->string + index);
    free(dest->string);
    dest->string = NULL;
    dest->string = new_str;
    dest->size = strlen(dest->string);
}
